package com.llpy.Service;

import com.llpy.dto.CommentDto;
import com.llpy.mapper.CommentMapper;
import com.llpy.mapper.UserMapper;
import com.llpy.pojo.Comment;
import com.llpy.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class CommentService {
    private final CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    public CommentService(CommentMapper commentMapper){
        this.commentMapper = commentMapper;
    }

    //保存评论，传入用户id和内容
    public Comment saveComment(String id, String content){
        User u = new User();
        //获得用户id
        Optional<User> byId = userMapper.findById(id);
        if (byId.isPresent()) {
            User user = byId.get();
            //将评论字段所需要的用户字段存入评论表
            u.setNickname(user.getNickname());
            u.setUserImg(user.getUserImg());
        }
//        新建一个评论
        Comment  comment = new Comment();
        u.setId(id);
        //获得评论时间
        LocalDateTime nowTime = LocalDateTime.now();
        comment.setTime(nowTime);
        comment.setUser(u);
        comment.setContent(content);
        //调用接口  保存评论
        return commentMapper.save(comment);
    }

    //更改精选评论
    public void updateComment(String id){
        //根据评论id更改root的值
        Optional<Comment> byId = commentMapper.findById(id);
        if (byId.isPresent()) {
            Comment comment = byId.get();
            //为1时，将他设为2
            if(comment.getRoot()==1){
                comment.setRoot(2);
            }else{
                comment.setRoot(1);
            }
            commentMapper.save(comment);
        }
    }

    //得到全部精选评论
    public Page<?> getCommentt(Pageable pageable){
        return commentMapper.findByRoot(1,pageable);  //直接调用接口，查询root为1的评论返回
    }

    //查询所有评论
    public List<Comment> getComment(){
        List<Comment> commentList= commentMapper.findAll();
        Collections.reverse(commentList);
        return commentList;
    }

    //删除评论，根据id
    public boolean deleteById(String id1) {
        commentMapper.deleteById(id1);
        return true;
    }

    //批量删除
    public boolean deleteById(List<String > id) {
        //遍历集合中的id，删除
        for (String s : id) {
            commentMapper.deleteById(s);
        }
        return true;
    }

    //获得分页数据
    public Page<Comment> findAll(Pageable pageable) {
        return commentMapper.findAll(pageable);
    }

    //模糊查询评论`
    public Page<Comment> findByNameRegex(String regex, Pageable pageable) {
        return commentMapper.findByContentRegex(regex,pageable);
    }

}
